package com.shouhuobao.bhi.stamp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.home.BannerImageAdapter;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.menu.WebViewActivity;
import com.collectplus.express.model.BannerBean;
import com.collectplus.express.model.Const;
import com.collectplus.express.model.StampOrderBean;
import com.collectplus.express.model.StampShopBean;
import com.collectplus.express.model.StampStoreBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import droid.frame.activity.title.TitleRes;
import droid.frame.utils.android.Log;
import droid.frame.utils.android.MathUtils;
import droid.frame.utils.lang.Str;
import droid.frame.view.ViewPagerExt;
import droid.frame.view.xlist.FooterListener;
import droid.frame.view.xlist.SListView;

/**
 * 邮票列表
 *
 * @author coffee<br>
 * 2015-7-2下午2:38:31
 */
public class StampStoreActivity extends BaseActivity2 implements OnClickListener {
    private HashMap<Integer, Integer> chooseStamp = new HashMap<Integer, Integer>();

    private SListView mListView;

    private StampStoreAdapter mAdapter;

    /**
     * 购物车
     */
    private ImageView mCartView;
    /**
     * 选购的数量
     */
    private TextView mUnpayText;
    /**
     * 支付价格
     */
    private TextView mOrderPrice;
    /**
     * 提交订单
     */
    private TextView mSubmitView;

    /**
     * 1.来自收银台
     */
    private int isFrom = 0;// 1从收银台界面过来的
    private ArrayList<StampStoreBean> stamps;

    private LayoutInflater mLayoutInflater = null;

    private ViewPagerExt mViewPager = null;
    private ViewGroup mStateLayout = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showLoadingDialog(null);
        AppHttp.getInstance().stampStoreList();
        AppHttp.getInstance().getAppBannerData(Const.BannerConfig.TOUDI_STAMPSHOP_APP);
        isFrom = getIntent().getIntExtra("from", 0);
        Log.d("11111", isFrom);
    }

    public HashMap<Integer, Integer> getChooseData() {
        return chooseStamp;
    }

    public void setChooseData(HashMap<Integer, Integer> newData) {
        chooseStamp = newData;
    }

    public void setChooseDataChange() {
        int chooseCount = chooseStamp.size();
        if (chooseCount > 0) {
            mCartView.setImageResource(R.drawable.stamp_cart_icon);
            mSubmitView.setEnabled(true);
            // mSubmitView.setBackgroundResource(R.drawable.app_button_selector);
            mUnpayText.setVisibility(View.VISIBLE);
            mUnpayText.setText(chooseCount + "");
            Iterator<Entry<Integer, Integer>> iterator = chooseStamp.entrySet().iterator();
            double totalPrice = 0;
            while (iterator.hasNext()) {
                Entry<Integer, Integer> next = iterator.next();
                Integer position = next.getKey();
                Integer pricePosition = next.getValue();
                StampStoreBean stampStoreBean = stamps.get(position);
                ArrayList<StampShopBean> stampShop = stampStoreBean.getStampList();
                StampShopBean shopBean = stampShop.get(pricePosition);
                totalPrice = MathUtils.add(totalPrice, shopBean.getTotalPrice());
            }
            mOrderPrice.setText("￥" + totalPrice);
        } else {
            mSubmitView.setEnabled(false);
            mCartView.setImageResource(R.drawable.stamp_cart_empty_icon);
            // mSubmitView.setBackgroundResource(R.drawable.app_button_bg_disable);
            mUnpayText.setVisibility(View.GONE);
            mOrderPrice.setText("￥0");
        }
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.stamp_store_main);
        super.findViewById();
        mLayoutInflater = LayoutInflater.from(this);
        getAppTitle().setCommonTitle("邮票商城", new TitleRes("购买记录", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StampStoreActivity.this, StampBuyHistoryActivity.class);
                startActivity(intent);
            }
        }));
        mCartView = (ImageView) findViewById(R.id.stamp_cart_img);
        mUnpayText = (TextView) findViewById(R.id.stamp_unpay);
        mOrderPrice = (TextView) findViewById(R.id.stamp_order_price);
        mSubmitView = (TextView) findViewById(R.id.stamp_order_submit);
        mSubmitView.setEnabled(false);
        // mSubmitView.setBackgroundResource(R.drawable.app_button_bg_disable);

        mListView = (SListView) findViewById(R.id.listview);
        mListView.setDivider(null);
        View headView = mLayoutInflater.inflate(R.layout.layout_stampstore_tips, null);
        TextView tipsTV = ((TextView) headView.findViewById(R.id.tipscontentTV));
        mViewPager = (ViewPagerExt) headView.findViewById(R.id.viewpager);
        mStateLayout = (ViewGroup) headView.findViewById(R.id.dot_layout);
        tipsTV.setText(Html.fromHtml(getString(R.string.stampstoretips)));
        tipsTV.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("title", "价格说明");
                startActivity(intent);
            }
        });
        mListView.addHeaderView(headView);
        //点击item暂时没有作用
        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            }
        });
        //刷新列表数据
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                AppHttp.getInstance().stampStoreList();
            }
        });
        //设置listview的底部监听
        mListView.setFooterListener(new FooterListener() {
            @Override
            public void onFooterVisible() {
            }
        });
        //这里可以设置为空，在父类的adapter中会进行非空判断创建集合
        mAdapter = new StampStoreAdapter(null, this);
        mListView.setAdapter(mAdapter);

        mCartView.setOnClickListener(this);
        mSubmitView.setOnClickListener(this);
        handleBanner(null);
        mViewPager.addOnPageChangeListener(mViewPager.new ViewPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < mViewPager.getChildCount(); i++) {
                    ImageView child = (ImageView) mStateLayout.getChildAt(i);
                    if (position == i) {
                        child.setImageResource(R.drawable.dot_light_2);
                    } else {
                        child.setImageResource(R.drawable.dot_dark_2);
                    }
                }
            }
        });
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.coupon_store://邮票列表返回来的数据
                cancelLoadingDialog();
                onRefreshComplete();
                final AppResult<StampStoreBean> result = JSON.parseList(msg.obj, StampStoreBean.class);
                if (result.isSuccess()) {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            stamps = result.getResultList();
                            mAdapter.setItems(stamps, true);
                        }
                    });

                } else {
                    showToast(result.getMessage());
                }
                return false;
            case MsgID.stamp_order:
                cancelLoadingDialog();
                final AppResult<StampOrderBean> orderResult = JSON.parser(msg.obj, StampOrderBean.class);
                if (orderResult.isSuccess()) {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            StampOrderBean stamps = orderResult.getResult();
                            Intent intent = new Intent(StampStoreActivity.this, StampOrderPayActivity.class);
                            intent.putExtra("stamp_order", stamps);
                            startActivityForResult(intent, 101);
                            // startActivity(intent);
                        }
                    });

                } else {
                    showToast(orderResult.getMessage());
                }
                return false;
            //邮票商场banner
            case MsgID.get_app_banner_data:
                if (msg.arg1 == Const.BannerConfig.TOUDI_STAMPSHOP_APP) {
                    final AppResult<BannerBean> bannerResult = JSON.parseList(msg.obj, BannerBean.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            handleBanner(bannerResult.getResultList());
                        }
                    });
                }
                return false;
            default:
                return super.handleMessage(msg);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.stamp_cart_img:
                if (chooseStamp.size() > 0) {
                    showChoosePop();
                }
                break;
            case R.id.pop_submit_order:
            case R.id.stamp_order_submit:
                if (chooseStamp.size() < 0) {
                    showToast("请选择邮票");
                    return;
                }
                String stampIds = getStampIds();
                showLoadingDialog("");
                AppHttp.getInstance().stampOrder(stampIds);
                break;
            default:
                break;
        }
    }

    /**
     * 获取选择的邮票id
     *
     * @return
     */
    private String getStampIds() {
        Iterator<Entry<Integer, Integer>> iterator = chooseStamp.entrySet().iterator();
        StringBuilder sb = new StringBuilder();
        while (iterator.hasNext()) {
            Entry<Integer, Integer> next = iterator.next();
            Integer position = next.getKey();
            StampStoreBean stampStoreBean = stamps.get(position);
            Integer pricePosition = next.getValue();
            ArrayList<StampShopBean> stampShop = stampStoreBean.getStampList();
            StampShopBean stampShopBean = stampShop.get(pricePosition);
            sb.append(stampShopBean.getSid()).append(",");
        }
        String stampIds = sb.toString();
        if (!Str.isEmpty(stampIds)) {
            return stampIds = stampIds.substring(0, stampIds.length() - 1);
        } else {
            return null;
        }
    }

    /**
     * 展示底部弹出的dialog
     */
    private void showChoosePop() {
        final View layout = LayoutInflater.from(this).inflate(R.layout.stamp_choose_pop, null);
        //
        final PopupWindow popwin = DialogMgr.createPopupWindow(this, layout);
        final LinearLayout chooseParent = (LinearLayout) layout.findViewById(R.id.stamp_choose_list);
        setPopData(layout, chooseParent);
        layout.findViewById(R.id.pop_bottom).setVisibility(View.VISIBLE);
        popwin.showAtLocation(this.findViewById(R.id.bottom_line), Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
        // 清除数据并隐藏pop
        layout.findViewById(R.id.stamp_choose_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseStamp.clear();
                setPopData(layout, chooseParent);
                setChooseDataChange();
                mAdapter.notifyDataSetChanged();
                popwin.dismiss();
            }
        });
        layout.findViewById(R.id.pop_cart_img).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popwin.dismiss();
            }
        });
    }

    /**
     * 根据选择的数据展示列表
     *
     * @param chooseParent
     */
    private void setPopData(final View layout, final LinearLayout chooseParent) {
        TextView orderPrice = (TextView) layout.findViewById(R.id.pop_price);
        TextView chooseCount = (TextView) layout.findViewById(R.id.pop_unpay);
        TextView submitView = (TextView) layout.findViewById(R.id.pop_submit_order);
        ImageView cartImage = (ImageView) layout.findViewById(R.id.pop_cart_img);
        submitView.setOnClickListener(this);
        chooseParent.removeAllViews();
        //注意：HashMap不支持Iterator所以要通过其他方式迭代Map中的Key和Value
        /**
         * 获取hs返回的Set视图
         * 非常注意：返回此映射中包含的映射关系的Set视图，对此Set视图的操作会反映到原来的HashMap
         */
        Iterator<Entry<Integer, Integer>> iterator = chooseStamp.entrySet().iterator();
        double totalPrice = 0;
        while (iterator.hasNext()) {
            Entry<Integer, Integer> next = iterator.next();
            final Integer position = next.getKey();
            Integer pricePosition = next.getValue();
            // 获取选择的邮票
            StampStoreBean stampStoreBean = stamps.get(position);
            ArrayList<StampShopBean> stampShop = stampStoreBean.getStampList();
            // 获取选择的价格
            StampShopBean stampShopBean = stampShop.get(pricePosition);
            totalPrice = MathUtils.add(totalPrice, stampShopBean.getTotalPrice());
            // 选择item
            View item = getLayoutInflater().inflate(R.layout.stamp_choose_item, null);
            TextView stampName = (TextView) item.findViewById(R.id.stamp_name);
            TextView stampPrice = (TextView) item.findViewById(R.id.stamp_price);
            stampName.setText(stampStoreBean.getName() + "-" + stampStoreBean.getSeries());
            stampPrice.setText(stampShopBean.getTotalPrice() + "");
            chooseParent.addView(item);
            stampPrice.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    chooseStamp.remove(position);
                    setPopData(layout, chooseParent);
                    setChooseDataChange();
                    mAdapter.notifyDataSetChanged();
                }
            });
        }

        if (chooseStamp.size() > 0) {
            cartImage.setImageResource(R.drawable.stamp_cart_icon);
            chooseCount.setVisibility(View.VISIBLE);
            chooseCount.setText(chooseStamp.size() + "");
            submitView.setEnabled(true);
        } else {
            cartImage.setImageResource(R.drawable.stamp_cart_empty_icon);
            chooseCount.setVisibility(View.GONE);
            submitView.setEnabled(false);
        }
        orderPrice.setText("￥" + totalPrice);
    }

    /**
     * 更新轮播图
     *
     * @param items
     */
    public void handleBanner(ArrayList<BannerBean> items) {
        if (mViewPager == null) {
            // 不作处理
        } else {
            BannerImageAdapter adapter = new BannerImageAdapter(items, getContext());
            ArrayList<View> pages = new ArrayList<View>();
            for (int i = 0; i < adapter.getCount(); i++) {
                View child = adapter.getView(i, null, mViewPager);
                pages.add(child);
            }
            mViewPager.setOffscreenPageLimit(pages.size());
            mViewPager.setViewItems(pages, false);
            // viewpager下面的点点
            mStateLayout.setVisibility(View.VISIBLE);
            mStateLayout.removeAllViews();
            for (int i = 0; i < adapter.getCount(); i++) {
                ImageView child = (ImageView) LayoutInflater.from(getContext()).inflate(R.layout.viewpager_dot, mStateLayout, false);
                if (i == 0) {
                    child.setImageResource(R.drawable.dot_light_2);
                } else {
                    child.setImageResource(R.drawable.dot_dark_2);
                }
                mStateLayout.addView(child);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 101 && resultCode == RESULT_OK) {
            if (isFrom == 0) {
                //从我的邮票跳转过来的，在支付完成后，跳转到我的邮票界面,暂时不知道为什么要写下面的代码
                //                Intent intent = new Intent(this, CouponListActivity.class);
                //                startActivity(intent);
            }
            if (isFrom == 1) {
                Intent intent = new Intent();
                setResult(Activity.RESULT_OK, intent);
            }
            finish();
        }
    }

}
